package com.u2b.business.net;

import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.u2b.kvdb.SaeFileHandler;


public class FileUpload
{
    public HashMap<String, Object> Upload(HttpServletRequest request, String[] textParams, String[] mimes, String[] sqlKeys, String domain)
    {
       
        ArrayList<InputStream> inputStreamList = new ArrayList<InputStream>();
        HashMap<String, Object> formField = new HashMap<String, Object>();
        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
        if (isMultipartContent)
        {
            FileItemFactory ff = new DiskFileItemFactory();
            ServletFileUpload sf = new ServletFileUpload(ff);
            try
            {
                List<FileItem> items = sf.parseRequest(request);
                for (FileItem item : items)
                {
                    if (item.isFormField())
                    {
                        for (int i = 0; i < textParams.length; i++)
                        {
                            if (textParams[i].equals(item.getFieldName()))
                            {
                                formField.put(textParams[i], URLDecoder.decode(item.getString(), "UTF-8"));
                            }
                        }

                    }
                    else
                    {
                        InputStream in = item.getInputStream();
                        inputStreamList.add(in);
                        System.err.println("fileUpload " + in != null);
                    }

                }
                int size = inputStreamList.size();
                if (size > 0)
                {
                    InputStream[] inputStrems = new InputStream[size];
                    for (int i = 0; i < size; i++)
                    {
                        inputStrems[i] = inputStreamList.get(i);
                    }
                    HashMap<String, Object> storagePaths = new HashMap<String, Object>();
                    storagePaths = new SaeFileHandler().saveToStorage(inputStrems, mimes, sqlKeys, domain);
                    formField.putAll(storagePaths);
                }
            }
            catch (Exception e)
            {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
        return formField;

    }
}
